package com.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.dao.ICustomerDao;
import com.dao.entity.Customer;
import com.service.ICustomerService;
import com.utils.commons.CopyProperties;
import com.utils.commons.Encoder;

@Service
public class CustomerServiceImpl implements ICustomerService{
	
	@Autowired
	private ICustomerDao customerDao;

	@Override
	public Customer saveCustomer(Customer c) {
		if(ObjectUtils.isEmpty(c)) {
			return null;
		}
		Customer old = customerDao.findById(c.getId()).orElse(new Customer());
		if(c.getPassword() != null && c.getPassword().length() > 0) {
			c.setPassword(Encoder.MD5FreeHex(c.getPassword()));
		}
		if((c.getPassword() == null || c.getPassword().length() == 0) && !ObjectUtils.isEmpty(c.getId())) {
			customerDao.findById(c.getId()).ifPresent(e -> {
				c.setPassword(e.getPassword());
			});
		}
		CopyProperties.nullNotCopy(c, old);
		return customerDao.save(old);
	}

	@Override
	public Customer findCustomer(Customer c) {
		if(c.getId() != null) {
			return customerDao.findById(c.getId()).orElse(new Customer());
		}
		if(c.getOpenId() != null) {
			return customerDao.findByOpenId(c.getOpenId());
		}
		return new Customer();
	}

	
}
